// JavaScript Document
/**
 * Jquery ready
 * Cac function javascript tren Zing Deal
 *
 * @author hungtd <hungtd@vng.com.vn>
 */

/**
 * Ham check email
 */
function validateEmail(id)
{
    var emailPattern = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
    return emailPattern.test(id);
}

/**
 * Ham check dien thoai di dong
 */
function validatePhone(id)
{
    var phonePattern = /^(\+([0-9])+\s)*(([0-9])+([-])*([0-9])+)+$/;
    return phonePattern.test(id);
}

/**
 * check validate password form register
 */
function validatePasswordRule(pwd1, pwd2)
{
    var kiem_tra = 0;
    var chu_thuong = 0;
    var chu_hoa = 0;
    var ky_tu = 0;
    var chu_so = 0;
    if(pwd1.val() != "" && pwd1.val() == pwd2.val()) {
        if(pwd1.val().length < 8 || pwd1.val().length > 32) {
            AlertZingDeal("Lỗi: Mật khẩu phải có độ dài từ 8 đến 32 ký tự (>=8 và <=32)!");            
            return -1;
        }
        // kiem tra pass co chu so hay khong
        re = /[0-9]/;
        if(!re.test(pwd1.val())) chu_so = 1;
        else chu_so = 1;
        // kiem tra pass co chu thuong hay khong
        re = /[a-z]/;
        if(!re.test(pwd1.val())) chu_thuong = 1;
        else chu_thuong = 1;
        // kiem tra pass co chu hoa hay khong
        re = /[A-Z]/;
        if(!re.test(pwd1.val())) chu_hoa = 1;
        else chu_hoa = 1;
        // kiem tra pass cho ky tu dac biet hay khong
        re = /[\W_]/;
        if(!re.test(pwd1.val())) ky_tu = 1;
        else ky_tu = 1;
    } else {
        AlertZingDeal("Lỗi: Xác nhận mật khẩu không chính xác!");        
        return -1;
    }
    kiem_tra = parseInt(chu_so) + parseInt(chu_thuong) + parseInt(chu_hoa) + parseInt(ky_tu);    
    if (kiem_tra < 3) return 0;
    return 1;
}

/**
 * check internet banking
 */
function checkIB()
{
    var amount_min = 50000;
    var amount_max = 100000000;
    var amount_devide = 10000; //var amount_devide = 10000;
    $('#ZingTransactionAmount').val($('#ZingTransactionAmount').val().replace(/\$|\,/g,''));
    if ($("input[name='banking_service']:checked").val() < 1 || parseInt($('#ZingTransactionAmount').val()) < amount_min || $('#ZingTransactionAmount').val() == '' || parseInt($('#ZingTransactionAmount').val()) > amount_max || parseInt($('#ZingTransactionAmount').val()) % amount_devide != 0 || isNaN(parseInt($('#ZingTransactionAmount').val()))) {
        var note = $('#account-not-exit').val();
        if (parseInt($('#ZingTransactionAmount').val()) < amount_min) {
            note = $('#alert-choose-amount-min').val();
        } else if ($('#ZingTransactionAmount').val() == '' || isNaN(parseInt($('#ZingTransactionAmount').val()))) {
            note = $('#alert-choose-amount').val();
        } else if (parseInt($('#ZingTransactionAmount').val()) % amount_devide != 0) {
            note = $('#alert-choose-amount-add').val();
        } else if (parseInt($('#ZingTransactionAmount').val()) > amount_max) {
            note = $('#alert-choose-amount-max').val();
        }                
        AlertZingDeal(note);
        $('#ZingTransactionAmount').val(formatCurrency($('#ZingTransactionAmount').val()));
        return false;
    }
    return true;
}

/**
 * Ham lay cookie
 */
function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + '=');
        if (c_start !=- 1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(';', c_start);
            if (c_end ==- 1) {
                c_end = document.cookie.length;
            }
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return '';
}

/**
 * HUNGTD
 * format currency
 */
function formatCurrency(num) {
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
        num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));
    //return (((sign)?'':'-') + '' + num + '.' + cents);
    return (((sign)?'':'-') + '' + num);

}

/**
 * hungtd - create cookie
 */
function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

/**
 * hungtd - read cookie
 */
function readCookie(c_name)
{
    var i,x,y,ARRcookies=document.cookie.split(";");
    for (i=0;i<ARRcookies.length;i++) {
        x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
        y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
        x=x.replace(/^\s+|\s+$/g,"");
        if (x==c_name) {
            return unescape(y);
        }
    }
    return false;
}

/**
 * hungtd - Get bought on deal view
 */
function getCountBought(deal_id)
{
    var aurl=__cfg('path_relative')+'deals/zd_count_bought/'+deal_id+'/cache:'+Math.floor(Math.random()*10000);

    var result = $.ajax({
            type: "GET",
            url: aurl,
            data: '',
            async: false
    }).responseText;
    if (result != 'ERROR') {
        $('.zingdeal-number-bought').html(result);
    }
}

/**
 * hungtd - Charge Card to Zing Deal Amount
 */
function ChargeCardToZingDeal(user, seri, code, captcha)
{
	maskBlackDiv('.tbox .PopupContentFrm');
    var aurl=__cfg('path_relative')+'zing_transactions/zd_charge_card';	
    var result = $.ajax({
            type: "GET",
            url: aurl,
            data: 'user='+user+'&zdseri='+seri+'&zdcode='+code+'&zdcaptcha='+captcha+'&cache='+Math.floor(Math.random()*10000),
            async: false
    }).responseText;
	
    if (result == 'SUCCESS')
        window.location.href = window.location.href;
}

/**
 * hungtd - get balance for zing
 */
function getBalanceZing()
{	
    var aurl=__cfg('path_relative')+'users/zd_get_balance_zing/'+'cache:'+Math.floor(Math.random()*10000);
	$.get(aurl, function(data) {
        $('.JsBalance').html(formatCurrency(data));
    });    
}

/**
 *
 * huydm - validate email
**/
function validateSubscriptions()
{
    var email = $('#SubscriptionEmail').val();
    var reg = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
    if(reg.test(email)){
        return true;
    } else {
        alert('Error Email');
        return false;
    }
}

/**
 * add email daily in ajax
 */
function AddEmailDailyAjax()
{
    var email = $('#SubscriptionEmail').val();
    var city_id = 44;
    var user_id = 0;
    var aurl=__cfg('path_relative')+'subscriptions/addmail';
    var reg = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
    if(reg.test(email)){
        $.post(aurl, {email: email, city_id: city_id, user_id: user_id},
        function(data){
            alert(data);
        });
    } else {
        alert('Xin nhập vào 1 email hợp lệ');
        return;
    }
}

/**
 * hungtd - Track Deal
 */
function trackDeal(deal_id)
{
    var aurl=__cfg('path_relative')+'deals/track_deal/'+deal_id+'/cache:'+Math.floor(Math.random()*10000);
    $.get(aurl, function(data) {
        data = data+'';
    });
}

/**
 * hungtd - notic error phone number
 */
function errorPhoneNumber()
{

}

/**
 * hungtd - Add facebook
 */
function getLikeBoxFacebook(facebook)
{       
    var data = '<div style="height: 10px;"></div><div class="deal zingdeal-faq no-deal"><div class="deal-bg round-15 clearfix">'+facebook+'</div></div>';
    $('.side2').append(data);
}
/**
 * hungtd - Add Zing Me
 */
function getLikeBoxZingMe()
{
    //var zingme = '<iframe scrolling="auto" frameborder="0" style="border: medium none; width: 230px; height: 339px;" allowtransparency="true" src="http://connect.me.zing.vn/vip/connect?uid=24868452"></iframe>';
    //var data = '<div style="height: 10px;"></div><div class="deal zingdeal-faq no-deal"><div class="deal-bg round-15 clearfix"><div class="header-deal-next"><div class="icon-zingdeal"></div><h2><span class="h2">Zing Me</span></h2></div>'+zingme+'</div></div>';
    //$('.side2').append(data);
}
/**
 * hungtd - like this deal on facebook
 */
function likeThisDealToFaceBook(url)
{
    var uri = encodeURI(url);
    //alert(uri);
    var data = '<iframe src="http://www.facebook.com/plugins/like.php?href='+uri+'&amp;layout=standard&amp;show_faces=false&amp;width=450&amp;action=like&amp;font=tahoma&amp;colorscheme=light&amp;height=35" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:35px;" allowTransparency="true"></iframe>';
    $('#zingdeal-like-this-deal').html(data);
}
/**
 * hungtd - like this deal on facebook Mobile
 */
function likeThisDealToFaceBookMB(url)
{
    var uri = encodeURI(url);
    //alert(uri);
    var data = '<iframe src="http://www.facebook.com/plugins/like.php?href='+uri+'&amp;layout=box_count&amp;show_faces=true&amp;width=100&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=65" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100px; height:65px;" allowTransparency="true"></iframe>';
    $('#zingdeal-like-this-deal').html(data);
}

/**
 * insert emoticon to discussion
 */
function insertEmoticon(a)
{
    var r = $('#TopicDiscussionComment').val();
    $('#TopicDiscussionComment').val(''+r+' '+a);
}

/* JS for order reservation*/
function showOrderResConfirm()
{
	var value = jQuery('#DealBuyForm input:radio:checked').val();
	if(value == 5){
		$('#zingdeal-popup-order-reservation').show('slow');
        return;
	}
}

/**
 * Danh sach user dat hang de thanh toan sau
 */
function list_order(){
	var city = $('#OrderReservationCity').val();
	var url = __cfg('path_absolute') + city + "/deal_user_tmps/list_order_reservation_ajax";
	$.ajax({
			url: url,
			success: function (data){
				$("#listOrderReservation").html(data);
			}
		}
	);
}

/**
 * COD confirm
 */
function CODConfirm()
{
    var deal_id = $('#DealDealId').val();
    var quantity = $('#DealQuantity').val();	 
    $('.JsCODMethod').show();
    $('.JsZingXuMethod').hide();
    // load data frome ajax
    var aurl=__cfg('path_relative')+'delivery_addresses/woadd/'+deal_id+'/quantity:'+quantity+'/cache:'+Math.floor(Math.random()*10000);
    $.get(aurl, function(data) {    	
    	$('.JsCODMethod').html(data);
    });
    // end load data from ajax
}

// check and add COD Address
function checkCODAddress()
{
	var i = 0;
	i += ShowNoteForm('#DAName', 0);
	i += ShowNoteForm('#DACityId', 0);
	i += ShowNoteForm('#DADistrictId', 0);
	i += ShowNoteForm('#DAWard', 0);
	i += ShowNoteForm('#DAHouseNumber', 0);
	i += ShowNoteForm('#DAStreetAddress', 0);
	i += ShowNoteForm('#DAPhone', 1);
		
	if (i == 7) {
		if (!validatePhone($('#DAPhone').val())) {
			$('#DAPhone').parent().children('.Note2').show();
			return 0;
		} else {
			$('#DAPhone').parent().children('.Note2').hide();
			return 1;
		}
	} else return 0;
}

// show note error of input form
function ShowNoteForm(form_input, is_note2)
{
	if ($(form_input).val() == '') {
		$(form_input).parent().children('.Note').show();
		if (is_note2 == 1) $(form_input).parent().children('.Note2').hide();
		return 0;
	} else {
		$(form_input).parent().children('.Note').hide();
		return 1;
	}
}

/**
 * Add dia chi giao hang cua user va check confirm code
 */
function AddDeliveryAddress()
{
	var confirm_code = '';
	// get value confirm code
	if ($('#input_confirm_cod_code').val() != '') confirm_code = $('#input_confirm_cod_code').val();
	if ($('#input_confirm_cod_code_email').val() != '') confirm_code = $('#input_confirm_cod_code_email').val();
	
    // check empty code
    if (confirm_code == '') return;
	
    // check COD confirm code
	$('#status-send-confirm-code').hide();
    $('#status-send-confirm-code').html("&nbsp;");
    
    var deal_id = $('#DealDealId').val();
    
	// check confirm code
	maskBlackWindow(0);
	$('#loading-send-confirm-code').attr('src', __cfg('path_static')+'static/img/blue-theme/loading_16x11.gif');
    var aurl_checkcode = __cfg('path_relative')+'deal_user_tmps/check_code_confirm_cod/'+deal_id+'/'+confirm_code+'/address_id:'+$('#DeliveryAddressAddressId').val()+'/cache:'+Math.floor(Math.random()*10000);
    $.get(aurl_checkcode, function(data_checkcode) {
        if (data_checkcode == '1') {
			// add Delivery address			                        					
			saveDeliveryAddress(1);		
        } else {
			maskBlackWindow(1);
            $('#loading-send-confirm-code').attr('src', __cfg('path_static')+'static/img/blue-theme/img-line.png');
            $('#status-send-confirm-code').html(data_checkcode);
			$('#status-send-confirm-code').show();
        }
    });
    // add dia chi giao hang    
}

/**
 * Add dia chi giao hang khong can check confirm code
 */
function AddDeliveryAddressNotConfirm()
{
	maskBlackWindow(0);
	saveDeliveryAddress(1);
}

// save ajax delivery address
function saveDeliveryAddress(show)
{	            
	var aurl=__cfg('path_relative')+'delivery_addresses/woadd/'+'cache:'+Math.floor(Math.random()*10000);
	$.post(aurl, {name: $('#DAName').val(), house_number: $('#DAHouseNumber').val(), street_address: $('#DAStreetAddress').val(), ward: $('#DAWard').val(), district_id: $('#DADistrictId').val(), message: $('#DAMessage').val(), phone: $('#DAPhone').val(), deliveryday: $('#DADeliveryDate').val(), auto_receive: $('#CheckRecieverOnCompany:checked').val(), receive_from: $('#DADeliveryFrom').val(), receive_to: $('#DADeliveryTo').val()},
    	function(data)
		{
			if (show == 1) {				
				// submit form mua hang
				if (data >= 1) {									
					$('#DealBuyForm').submit();
				}
				else {
					maskBlackWindow(1);
				}
			}
	    }
	);
}

/**
 * Tao mask black tren obj
 */
function maskBlackDiv(div, omaks)
{
	if (omaks == 1)
		$(div).unmask();	
	else 
		$(div).mask('Vui lòng chờ ...');	
}

/**
 * Tao man hinh black tren zing deal
 */
function maskBlackWindow(omaks) {maskBlackDiv('body', omaks);}

/**
 * Xu ly phan user chon ngan hang de nap tin vao Zing Deal
 */
function chooseBanking(id) {    
    $('#'+id).attr('checked', true);
    $('.listbanks li').removeClass('Active');
    $('.'+id).addClass('Active');
}

/**
 * Phan thanh toan qua COD
 * Chuc nang gui ma xac don hang
 */
function SendConfirmCodeCOD()
{   
	// layout default
	$('#status-send-confirm-code-email').hide();     
    $('#status-send-confirm-code-email').html("&nbsp;");
    $('#loading-send-confirm-code-email').attr('src', __cfg('path_static')+'static/img/blue-theme/loading_16x11.gif');
	// get data
    var deal_id = $('#DealDealId').val();    
    var captchacodejs = $('#DeliveryAddressCaptcha').val();
    var email = $('#DeliveryAddressEmail').val();
	// check email
    if (email == '' || !validateEmail(email)) {
        $('#status-send-confirm-code-email').html('Bạn chưa điền địa chỉ email hoặc địa chỉ email của bạn không đúng. Vui lòng điền chính xác địa chỉ email của bạn.');
		$('#status-send-confirm-code-email').show();
        $('#loading-send-confirm-code-email').attr('src', __cfg('path_static')+'static/img/blue-theme/img-line.png');
    } else {
        var aurl=__cfg('path_relative')+'deal_user_tmps/confirmcod/'+deal_id+'/captchacode:'+captchacodejs+'/email:'+email+'/cache:'+Math.floor(Math.random()*10000);
        $.get(aurl, function(data) {
			$('#status-send-confirm-code-email').html(data);
			$('#status-send-confirm-code-email').show();
            $('#loading-send-confirm-code-email').attr('src', __cfg('path_static')+'static/img/blue-theme/img-line.png');            
        });
    }
}

/**
 * User cancel don hang COD
 */
function getConfirmCancelDelivery(id, page)
{
    $('.delivery_id').val(id);
    $('.delivery_page').val(page);
    var htmltext = '<div class="frmNapThe"><div style="padding-bottom: 15px; text-align: center;">'+$('.question').val()+'</div>';
    htmltext += '<div style="text-align: center;"><input type="button" class="BtnXacNhan" style="float:none;margin:0;" onClick="CancelDelivery(\''+id+'\', \''+page+'\')" value=" " /></div></div>';    
	AlertZingDeal(htmltext);    
}

/**
 * User cancel don hang COD
 */
function CancelDelivery(id, page)
{
    var aurl=__cfg('path_relative')+'deal_user_tmps/cancel_delivery/'+Math.floor(Math.random()*10000000000);
    $.post(aurl, {delivery_id: id},
    function(data){
        var status = data.substr(0 ,1);
        var message = data.substr(1, data.length);        
        AlertZingDeal(message);
        if (status == 1) {
            window.location.href = window.location.href;
//            var aurl2=__cfg('path_relative')+'deal_user_tmps/deliveryindex/'+Math.floor(Math.random()*10000000000)+'/page:'+page;
//            $.get(aurl2, function(data2) {
//                $('.JsAjaxContent').html(data2);
//                AlertHide();
//            });
        }
    });
}

// alert cho input
function alertInput(obj) 
{
	AlertZingDeal($(obj).attr('alert'));
}

// refresh captcha
function reCaptcha()
{
    var nbran = Math.floor(Math.random()*10000000000);
    $('#sVerifyImg').attr('src', __cfg('path_relative')+'static/img/blue-theme/loading_16x11.gif');
    var aurl=__cfg('path_relative')+'deal_images/zd_captcha_charge/'+nbran;
    $('#sVerifyImg').attr('src', aurl);
}

// Zing Deal popup
function PopUpZD(url_html, url)
{
	if (url == 1) {
    	TINY.box.show({url:url_html,width:514,topsplit:3,fixed:false,animate:false});    	
    } else {
    	TINY.box.show({html:url_html,width:514,topsplit:3,fixed:false,animate:false});
    }
}

// alert cua Zing Deal
function AlertZingDeal(msg, title)
{
	if (!title) {title = JsLangZD.notic_title}
	var html_note = '<div class="InnerContent"><h3 class="TitleMain">'+title+'</h3><div class="PopupContentFrm">'+msg+'</div></div>';
    PopUpZD(html_note, 0);
}

// set top
function AlertZingDealTop(msg, title, top)
{
    if (!title) {title = JsLangZD.notic_title}
	var html_note = '<div class="InnerContent"><h3 class="TitleMain">'+title+'</h3><div class="PopupContentFrm">'+msg+'</div></div>';
    TINY.box.show({html:html_note,width:514,top:top,fixed:false,animate:false});
}

// hide alert Zing Deal
function AlertHide() {TINY.box.hide();$('.message').hide();}

/**
 * Chuyen chuoi ngay thang nam sang Object cua javascript
 */
function strToOjectDate(date_time)
{
    var arr_datetime = new Array();	
	var arr_date = new Array();
	var arr_time = new Array();
	
    arr_datetime = date_time.split(' ');
    arr_date = arr_datetime[0].split('-');
	arr_time = arr_datetime[1].split(':');
	
	var austDay = new Date();
	austDay = new Date(arr_date[0], arr_date[1]-1, arr_date[2], arr_time[0], arr_time[1], arr_time[2]);
	
	return austDay;
}

// show childrend discussion
function childrentDiscussion(id)
{
    var aurl=__cfg('path_relative')+'topic_discussions/children_discussion/'+id+'/cache:'+Math.floor(Math.random()*10000);
    $.get(aurl, function(data) {
        if (data != 'ERROR') {
            $('#childrent-dicussion-'+id).html(data);
            $('#childrent-dicussion-'+id).show();
        }
    });
}

// add topic discussion
function SendTopicComment(parent_id)
{
	// get data
	var topic_id = $('#TopicId').val();
	var message = $('#TopicComment'+parent_id).val();
	// check message
	if (message.toString().replace(/\$|\ /g,'').length < 20) {
		AlertZingDeal(JsLangZD.alert_min_20_char);
		return false;
	}
	// check login
	if (isUserLogin() == false) {
		showFormQuickLogin();
		return false;
	}		
	// get url
	var aurl=__cfg('path_relative')+'topic_discussions/ajaxadd/'+'cache:'+Math.floor(Math.random()*10000);
	$.post(aurl, {parent_id: parent_id, topic_id: topic_id, message: message},
    function(data){
		$('#TopicComment'+parent_id).val('');
        AlertZingDeal(data);
    });
}

// show div
function ShowHideDiv(div_1, div_2) {$(div_1).show();$(div_2).hide();}

// submit form
function submitFormPopup(varform) {maskBlackWindow(0);$(varform).submit();}

// show form login nhanh
function showFormQuickLogin()
{
	aurl=__cfg('path_relative')+'users/ajaxlogin';
	PopUpZD(aurl, 1);
}

// check login cookie SSO
function isUserLogin()
{
	var uin = getCookie('uin');
    var username = getCookie('ZDUSERNAME');
	if (uin || username) return true;
	return false;
}

// function check 
function checkGiftForm()
{
	var i = 0;
	i += ShowNoteForm(getFormValue('Jsgift_from', 0, 1));
	i += ShowNoteForm(getFormValue('Jsgift_to', 0, 1));
	i += ShowNoteForm(getFormValue('Jsgift_mail', 0, 1), 1);
	i += ShowNoteForm(getFormValue('Jsgift_phone', 0, 1), 1);
	
	if (i == 4) {
		// check email
		if (!validateEmail(getFormValue('Jsgift_mail'))) {
			$(getFormValue('Jsgift_mail', 0, 1)).parent().children('.Note2').show();
			return 0;
		} else {
			$(getFormValue('Jsgift_mail', 0, 1)).parent().children('.Note2').hide();			
		}
		
		// check phone
		if (!validatePhone(getFormValue('Jsgift_phone'))) {
			$(getFormValue('Jsgift_phone', 0, 1)).parent().children('.Note2').show();
			return 0;
		} else {
			$(getFormValue('Jsgift_phone', 0, 1)).parent().children('.Note2').hide();			
		}
				
		return 1;
	} else return 0;		
}

// function get value form input
function getFormValue(name, isSelect, isObj)
{
	if (isObj == 1) {
		if (isSelect == 1) {
			return 'select[name='+name+']';
		} else {
			return 'input[name='+name+']';
		}
	} else {
		if (isSelect == 1) {
			return $('select[name='+name+']').val();
		} else {
			return $('input[name='+name+']').val();
		}	
	}			
}

// check account Zing Deal
function checkAccountZingDeal(inputUsername)
{	
	var user = inputUsername.val(); 
	// check value
	if (user == '' || user.length < 4) {
		inputUsername.css({border:"1px solid #FF0000"});
		return false;
	}
	// status border		
	inputUsername.css({border:"1px solid #CFCFBD"});
	// check by ajax
	var aurl=__cfg('path_relative')+'zing_transactions/zd_check_user/'+user+'/cache:'+Math.floor(Math.random()*10000);
	$.get(aurl, function(data) {
		if (data == 'ERROR') {
			inputUsername.css({border:"1px solid #FF0000"});            
            inputUsername.siblings('.Note').show();
		} else {				
			inputUsername.css({border:"1px solid #89B4D6"});
            inputUsername.siblings('.Note').hide();
		}
	});
}

// check account in Zing ID
function checkAccountZingID(inputUsername)
{
	var user = inputUsername.val(); 
	// check value
	if (user == '' || user.length < 4) {
		inputUsername.css({border:"1px solid #FF0000"});
		return false;
	}
	// status border		
	inputUsername.css({border:"1px solid #CFCFBD"});
	// check by ajax
	var aurl=__cfg('path_relative')+'users/zd_check_user/'+user+'/cache:'+Math.floor(Math.random()*10000);
	$.get(aurl, function(data) {
		if (data == 'SUCCESS') {
			inputUsername.css({border:"1px solid #89B4D6"});
            inputUsername.siblings('.Note').show();            
            inputUsername.siblings('.Note').css("color", "#608BC0");
            inputUsername.siblings('.Note').html(JsLangZD.zing_id_ok);            
		} else {
            inputUsername.siblings('.Note').show();
            inputUsername.siblings('.Note').css("color", "#FF0000");
			inputUsername.css({border:"1px solid #FF0000"});
            if (data == 'ERRORZD') 
                inputUsername.siblings('.Note').html(JsLangZD.zing_id_not_allow);
            else inputUsername.siblings('.Note').html(JsLangZD.zing_id_exit);
		}
	});
}

// get string from date
// str <=> 'd-m-Y'
function toTimestamp(strDate)
{
	if (strDate == '') return '';
    var strFormat = formatDateUSA(strDate, '/');
	var datum = Date.parse(strFormat);
 	return datum/1000;
}

// change d-m-Y => Y-m-d
function formatDateUSA(str, c) 
{
    var arr = str.split('-');
    return arr[2] + c + arr[1] + c + arr[0];
}

// chọn các sub deal khác
function chooseOtherChildrenDeal(deal_parent_id)
{
    var is_gift = parseInt($('#DealIsGift').val());
    var $div = $('.JsBuyDealShowChildrenDeal');
    var width = $div.parent().width() - 1;
    $div.width(width);
    var aurl=__cfg('path_relative')+'ajaxpages/choose_childrendeal/'+deal_parent_id+'/'+is_gift+'/cache:'+Math.floor(Math.random()*10000);    
    $div.load(aurl);    
    $div.show();    
}

/* Customize heigh of iframe ZingMe*/
function zmGH() {
    _document = window.document;
    var newHeight;
    if (isNaN(newHeight)) {
        var body = _document.body;
        var docEl = _document.documentElement;
        if (_document.compatMode === 'CSS1Compat' && docEl.scrollHeight)
            newHeight = docEl.scrollHeight;
        else {
            var sh = docEl.scrollHeight;
            var oh = docEl.offsetHeight;
            if (docEl.clientHeight !== oh) {
                sh = body.scrollHeight;
                oh = body.offsetHeight;
            }
            newHeight = sh;
        }
    }
    return newHeight;
}

function zmResize(appname, h) {
    if (h == undefined || h == null) h = zmGH();
    var nh = "<iframe border=\"0\" style=\"display:none;\" src=\"http://me.zing.vn/rs_proxy.html?id=1#iframe_dst=parent&domain=zing.vn&message=" + appname + "#" + h + "\"></iframe>";
    document.write(nh);
}

function ResizeFrame()
{
    try {
        var h = $('#ZingDealApp').height();		
        var options;// = {host: "zmapp.deal.zing.vn"};
        zmXCall.resizeParent({id:"zingdeal", height: h+10}, options);
    } catch (ex) {}
}
/* End customize heigh of iframe ZingMe*/